package com.lc.rongzecaifu.fragment;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.rongzecaifu.MyApplication;
import com.lc.rongzecaifu.activity.AdvertisingActivity;
import com.lc.rongzecaifu.activity.NewsActivity;
import com.lc.rongzecaifu.activity.NewsActivity2;
import com.lc.rongzecaifu.activity.TiroAndExperienceActivity;
import com.lc.rongzecaifu.adapter.HomeListRecyAdapter;
import com.lc.rongzecaifu.adapter.IconListRecyAdapter;
import com.lc.rongzecaifu.conn.JsonAccessToken;
import com.lc.rongzecaifu.conn.JsonIndex;
import com.lc.rongzecaifu.rongzecaifu.R;
import com.lc.rongzecaifu.toast.LovelyToast;
import com.lc.rongzecaifu.ui.RegistWebActivity;
import com.lc.rongzecaifu.view.FullyLinearLayoutManager;
import com.lc.rongzecaifu.view.MarqueeView;
import com.lc.rongzecaifu.view.SimpleDividerItemDecoration;
import com.zcx.helper.activity.AppV4Fragment;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;

import static com.lc.rongzecaifu.rongzecaifu.R.id.marqueeView;

/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends AppV4Fragment implements View.OnClickListener, ScrollView.OnTouchListener {
    public final static String FLAG = "IsTiro";

    @Bind(R.id.iv_mailer)
    ImageView ivMailer;
    @Bind(R.id.ll_01)
    LinearLayout ll01;
    @Bind(R.id.ll_02)
    LinearLayout ll02;
    @Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    //下边banner图片
   /* @Bind(R.id.convenientBanner_middle)
    ConvenientBanner convenientBanner_middle;*/
    @Bind(R.id.lv_home_list)
    RecyclerView lv_home_list;
    @Bind(R.id.news_xinshou)
    LinearLayout news_xinshou;

    private FullyLinearLayoutManager layoutManager;
    private List<JsonIndex.Info.Borrow_list> menuListContent = new ArrayList<>();

    private HomeListRecyAdapter homeListAdapter;

    private String news_id;

    private OnDataTransmissionListener mListener;
    @Bind(R.id.iv_camera)
    SimpleDraweeView iv_camera;
    private MarqueeView verticalSwitchTextView1;


    public static List<String> noticeList = new ArrayList<>();

    List<String> mDatas;


    List<JsonIndex.Info.notice> list_notice = new ArrayList<>();


    @Bind(R.id.store_house_ptr_frame)
    PtrFrameLayout store_house_ptr_frame;
    private PtrClassicDefaultHeader header;

    @Bind(R.id.scroll_layout)
    ScrollView scroll_layout;

    //判断Scrollview是否滑动
    private int y;

    //中间图片的url

    private String banner_middle_url;
    //中间图片的title
    private String banner_middle_title;

    private List<JsonIndex.Info.Linek_img> link_img = new ArrayList<>();

    //首页弹出的dialog
    Dialog dia;
    //图标

    @Bind(R.id.recycleview_icon)
    RecyclerView recycleview_icon;

    public FirstFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) inflater.inflate(R.layout.fragment_first, null)));
        ButterKnife.bind(this, view);
        lv_home_list.setFocusable(false);

        // homeListAdapter = new HomeListAdapter(getContext(), menuListContent);
        //  lv_home_list.setAdapter(homeListAdapter);


        //iv_camera.setImageURI(Uri.parse("http://vhost106.zihaistar.com/UF/Uploads/Ad/20170327140958795.jpg"));
        verticalSwitchTextView1 = (MarqueeView) view.findViewById(marqueeView);

        lv_home_list.setLayoutManager(new LinearLayoutManager(getContext()));
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.line_divider);
        lv_home_list.addItemDecoration(new SimpleDividerItemDecoration(getActivity(), drawable, 2));
        homeListAdapter = new HomeListRecyAdapter(getContext(), menuListContent);
        lv_home_list.setNestedScrollingEnabled(false);
        lv_home_list.setAdapter(homeListAdapter);
//recycleview_icon

        header = new PtrClassicDefaultHeader(getActivity());

        // header = new PtrClassicDefaultHeader(getActivity());
        store_house_ptr_frame.setHeaderView(header);

        mDatas = new ArrayList<String>();
        for (int i = 'A'; i < 'z'; i++) {
            mDatas.add("" + (char) i);
        }
        layoutManager = new FullyLinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleview_icon.setLayoutManager(layoutManager);
        recycleview_icon.setEnabled(false);
        initListener();

        initLinstener2();
        if (MyApplication.myPreferences.readStatus().equals("9")) {
            Context context = getContext();
            dia = new Dialog(context, R.style.edit_AlertDialog_style);
            //  dia.setContentView(R.layout.activity_start_dialog);
            dia.setContentView(MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.activity_start_dialog, null)));

            LinearLayout layout_close = (LinearLayout) dia.findViewById(R.id.layout_close);
            layout_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dia.cancel();// 关闭弹出框
                }
            });

            Button btn_jump = (Button) dia.findViewById(R.id.btn_jump);
            btn_jump.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("url", MyApplication.myPreferences.readRegistUrl());
                    intent.setClass(getActivity(), RegistWebActivity.class);
                    startActivity(intent);
                }
            });


            dia.show();

            dia.setCanceledOnTouchOutside(true); // Sets whether this dialog is
            Window w = dia.getWindow();
            WindowManager.LayoutParams lp = w.getAttributes();
            lp.x = 0;
            lp.y = 40;
            dia.onWindowAttributesChanged(lp);


        } else {

        }


        return view;
    }


    private void initLinstener2() {


        store_house_ptr_frame.setPtrHandler(new PtrHandler() {


            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                //      int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibletemPosition();

                if (y == 0) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
                } else {
                    return false;
                }


                //return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);


            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //  UtilToast.show(getContext(), "刷新开始");


                getAccessToken();


            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }


    private void getAccessToken() {
        new JsonAccessToken("index/index", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initData(info.access_token);
                    } else {
                        // UtilToast.show(getActivity(), "安全验证失败！");
                        LovelyToast.makeText(getActivity(), "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //  UtilToast.show(getActivity(), "安全验证失败！");
                LovelyToast.makeText(getActivity(), "安全验证失败！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(getActivity(), false);
    }

    private void initData(String access_token) {
        new JsonIndex(access_token, new AsyCallBack<JsonIndex.Info>() {
            @Override
            public void onSuccess(String toast, int type, final JsonIndex.Info info) throws Exception {


                if (info != null) {


//                   menuListContent.clear();
//                    menuListContent.addAll(info.borrow_list);
                    menuListContent.clear();
                    menuListContent.addAll(info.borrow_list);
                    link_img.clear();
                    link_img.addAll(info.friend_list);


                    news_id = info.news_id;
                    list_notice.addAll(info.notice);

                    recycleview_icon.setAdapter(new IconListRecyAdapter(getContext(), link_img));


                    convenientBanner.setPages(
                            new CBViewHolderCreator<LocalImageHolderView>() {
                                @Override
                                public LocalImageHolderView createHolder() {
                                    return new LocalImageHolderView();
                                }
                            }, info.banner).setPageIndicator(new int[]{R.mipmap.ic_dots_uncheck, R.mipmap.ic_dots_check})
                            //设置指示器的方向
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL).setCanLoop(true);

                    for (int i = 0; i < info.notice.size(); i++) {
                        noticeList.add(info.notice.get(i).title);
                    }
//                    verticalSwitchTextView1.startWithList(noticeList);
                    verticalSwitchTextView1.startWithList(noticeList);
                    verticalSwitchTextView1.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position, TextView textView) {
                            if (TextUtils.isEmpty(noticeList.get(position))) {

                            } else if (noticeList.size() == 0) {

                            } else {
                                Intent intent = new Intent();
                                intent.putExtra("title", noticeList.get(position));
                                intent.putExtra("url", "http://www.rongzecf.com/api/index/article_content?id=" + info.notice.get(position).id + "&show_type=article");
                                intent.setClass(getActivity(), AdvertisingActivity.class);
                                startActivity(intent);
                            }


                        }
                    });
                    iv_camera.setImageURI(Uri.parse(info.banner_middle.get(0).img));

                    banner_middle_url = info.banner_middle.get(0).url;
                    banner_middle_title = info.banner_middle.get(0).title;
                    //中间图片的url


                }

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                store_house_ptr_frame.refreshComplete();
                homeListAdapter.notifyDataSetChanged();
            }

        }).execute(getActivity(), false);
    }

    private void initListener() {
        ll01.setOnClickListener(this);
        ll02.setOnClickListener(this);
        ivMailer.setOnClickListener(this);
        news_xinshou.setOnClickListener(this);
        scroll_layout.setOnTouchListener(this);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void getClick() {
     /*   RxView.clicks(btn_first)
                .throttleFirst(2, TimeUnit.SECONDS)   //两秒钟之内只取一个点击事件，防抖操作
                .subscribe(new RecordingObserver<Object>() {
                    @Override
                    public void onNext(Object o) {
                        super.onNext(o);
//                        Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();

                        startActivity(new Intent(MainActivity.this, SearchActivity.class));

                    }


                });*/

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_01:
                EventBus.getDefault().post(1);
                break;
            case R.id.ll_02:
                //   EventBus.getDefault().post(0);
                Intent intent2 = new Intent();
                intent2.putExtra(FLAG, true);
                intent2.setClass(getActivity(), TiroAndExperienceActivity.class);
                startActivity(intent2);
                break;
            case R.id.iv_mailer:
                if (!TextUtils.isEmpty(news_id)) {
                    Intent intent = new Intent();
                    intent.putExtra("id", news_id);
                    intent.setClass(getActivity(), NewsActivity.class);
                    startActivity(intent);
                } else {
                    getAccessToken();
                }
                break;
            case R.id.news_xinshou:

             /*   LovelyToast.makeText(getActivity(), "点击了新闻区！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);*/

                if (!TextUtils.isEmpty(news_id)) {
                    Intent intent = new Intent();
                    intent.putExtra("id", news_id);
                    intent.setClass(getActivity(), NewsActivity2.class);
                    startActivity(intent);
                } else {
                    getAccessToken();
                }
                break;
            case R.id.iv_camera:


              /*  Intent intent = new Intent();
                intent.putExtra("title", banner_middle_title);
                intent.putExtra("url", banner_middle_url);


                intent.setClass(getActivity(), AdvertisingActivity.class);
                getActivity().startActivity(intent);*/
                break;

        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        y = v.getScrollY();

        return false;
    }

    public class LocalImageHolderView implements Holder<JsonIndex.Info.BannerListContent> {
        private SimpleDraweeView imageView;

        @Override
        public View createView(Context context) {
            imageView = new SimpleDraweeView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, final JsonIndex.Info.BannerListContent listContent) {
            imageView.setImageURI(Uri.parse(listContent.img));
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("title", listContent.title);
                    intent.putExtra("url", listContent.url);
                    /*intent.putExtra("url", listContent.url);

                    Log.d(listContent.url, "88888888888888888888888888");*/
                    intent.setClass(getActivity(), AdvertisingActivity.class);
                    getActivity().startActivity(intent);
                }
            });
        }
    }


    public class LocalImageHolderViewMiddle implements Holder<JsonIndex.Info.BannerMiddle> {
        private SimpleDraweeView imageView;

        @Override
        public View createView(Context context) {
            imageView = new SimpleDraweeView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, final JsonIndex.Info.BannerMiddle listContent) {
            imageView.setImageURI(Uri.parse(listContent.img));
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("title", listContent.title);
                    intent.putExtra("url", listContent.url);

                    intent.setClass(getActivity(), AdvertisingActivity.class);
                    getActivity().startActivity(intent);
                }
            });


        }
    }


    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(3000);
        getAccessToken();

    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }

    //接口回调的方法
    public interface OnDataTransmissionListener {
        public void dataTransmission(String data);
    }

    public void setOnDataTransmissionListener(OnDataTransmissionListener mListener) {
        this.mListener = mListener;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
//        dia.dismiss();
//        dia = null;
    }
}
